package org.chl.sqlsession.sqltemplate.script;

import org.chl.sqlsession.sqltemplate.core.Context;
import org.chl.sqlsession.sqltemplate.token.GenericTokenParser;

public class TextFragment implements SqlFragment {

	private String sql;

	public TextFragment(String sql) {
		this.sql = sql;
	}

	@Override
	public boolean apply(final Context context) {

		GenericTokenParser parser = new GenericTokenParser("${", "}",
				content -> {
                    Object value = OgnlCache.getValue(content,
                            context.getBinding());
                    return value == null ? "null" : value instanceof CharSequence ? String.format("'%s'", value.toString().replaceAll("(?<!\\\\)'", "\\\\'")) : value.toString();
                });
		context.appendSql(parser.parse(sql));
		return true;
	}

}
